<?php
final class dbMysql extends dbBase{
	private $server = '';
	private $user = '';
	private $pass = '';
	private $link = '';
	private $s_dbname = '';
	
	public function __construct($s_server, $s_user, $s_pass, $s_dbname){ 
		$this->server = $s_server;
		$this->user   = $s_user;
		$this->pass   = $s_pass;
		$this->s_dbname = $s_dbname;
		$this->link = mysql_connect($this->server, $this->user, $this->pass, true);
		if(!is_resource($this->link)){
			$this->addError('Try Connect. Fail.', -7);
		}else{
			mysql_set_charset('utf8', $this->link);
			#mysql_query('SET NAMES utf8', $this->link);
		}
		if(!mysql_select_db($this->s_dbname, $this->link))$this->addError('Error to select database', -4);
	}
	
	function query($s_sql){
		$this->r_response = mysql_query($s_sql, $this->link);
		if (!$this->r_response) {
			$this->addError($s_sql);
			return false;
		}
		if(is_bool($this->r_response))return $this->r_response;
		$a_temp= array();
		while ($a_row = mysql_fetch_object($this->r_response)) {
			$a_temp[] = $a_row;
		}
		mysql_free_result($this->r_response);
		return $a_temp;
	}

	function getFields($s_table){
		$a_tmp=array();
		$s_sql=sprintf('DESCRIBE  %.35s', $this->safe($s_table));
		$a_response = $this->query($s_sql);
		
		foreach($a_response as $o_val){
			$o_tmp=new stdClass();
			$o_tmp->name = $o_val->Field;
			$o_tmp->isnull = $o_val->Null =='NO'?false:true;
			$o_tmp->iskey = $o_val->Key == 'PRI'?true:false;
			$o_tmp->type = $o_val->Type;
			$a_tmp[] = $o_tmp;
		}
		return $a_tmp;
	}

	function safe($s_str){
		return mysql_real_escape_string($s_str, $this->link);
	}

	function addError($s_sql='', $i_number = 1, $s_str=''){
		$this->error = 1;
		$this->sError = empty($s_str)?mysql_error($this->link). ". <strong> $s_sql</strong>": $s_sql;
		throw new ABException($this->sError);
	}

	function __destruct() {
		if(is_resource($this->link))mysql_close($this->link);
	}
} 
